#include <limits.h> // USHRT_MAX
#include <history.h>
#include <turtle.h>
#include <stdio.h>
#include <string.h>

int DoTurtle(HISTORY *h, TURTLE *t, unsigned short n)
{
	int i, j, k;
	double double_var1, double_var2, double_var3;


	printf("Calculating TR ... ");
	// TR = 『今日最高與今日最低的距離』、『前日收盤與今日最高的距離』、『前日收盤與今日最低的距離』取最大的
	for( i=n-2; i>=0; i--)
	{
		// 這幾個值是 0 表示缺資料，不應該會這樣才對
		if( h[i].high==0 || h[i].low==0 || h[i+1].close==0 )
		{
			if(h[i].high==0) printf("%d/%d/%d's high is 0.\n", h[i].year, h[i].month, h[i].day);
			if(h[i].low==0) printf("%d/%d/%d's low is 0.\n", h[i].year, h[i].month, h[i].day);
			if(h[i+1].close==0) printf("%d/%d/%d's close is 0.\n", h[i+1].year, h[i+1].month, h[i+1].day);
			return -1;
		}

		// 算絕對值
		double_var1 = (h[i].high>h[i].low)?(h[i].high-h[i].low):(h[i].low-h[i].high);
		double_var2 = (h[i].high>h[i+1].close)?(h[i].high-h[i+1].close):(h[i+1].close-h[i].high);
		double_var3 = (h[i+1].close>h[i].low)?(h[i+1].close-h[i].low):(h[i].low-h[i+1].close);

		// 找出最大值
		double_var1 = double_var2>double_var1?double_var2:double_var1;
		double_var1 = double_var3>double_var1?double_var3:double_var1;

		// 回傳
		t[i].tr = double_var1;
	}
	printf("OK\n");


	printf("Calculating ATR ... ");
	// ATR = ( 前日ATR × (n-1) + 今日TR ) / n，第一個 ATR 由於沒有『前日ATR』可以參考，所以直接算n日平均。
	for(i=n-1; i>=n-20; i--)
		t[n-20].atr += t[i].tr;
	t[n-20].atr /= 20;
	for(i=n-20-1; i>=0; i--)
		t[i].atr = (t[i+1].atr * (20-1) + t[i].tr)/20;
	printf("OK\n");



	printf("Calculating Breakout ... ");
	for(i=0; i<MAX_HISTORY; i++)
		memset(&t[i].breakout, 0xFF, sizeof(t[i].breakout));

	for(i=1; i<sizeof(t[0].breakout.high)/sizeof(t[0].breakout.high[0]); i++)
	{
		for(j=n-1-(i-1); j>=0; j--)
		{
			for(k=j+i-1; k>=j; k--)
			{
				if(t[j].breakout.high[i]<0xFFFF)
					t[j].breakout.high[i] = (h[t[j].breakout.high[i]].close<h[k].close)?k:t[j].breakout.high[i];
				else
					t[j].breakout.high[i] = k;
				
				if(t[j].breakout.low[i]<0xFFFF)
					t[j].breakout.low[i] = (h[t[j].breakout.low[i]].close>h[k].close)?k:t[j].breakout.low[i];
				else
					t[j].breakout.low[i] = k;
				
			}
		}
	}
	printf("OK\n");

	return 0;
}
